package net.example.lesson6.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangeCase {

    static final Exchanger<List<String>> exgr = new Exchanger<>();

    public static void main(String[] args) {

        new Thread(() -> {
            try {
                List<String> list = new ArrayList<>();
                list.add("A1");
                list.add("A2");
                System.out.println("交换前A的数据为：");
                for (String item : list) {
                    System.out.println("A" + ":" + item);
                }
                list = exgr.exchange(list);//交换数据

                System.out.println("交换后A的数据为：");
                for (String item : list) {
                    System.out.println("A" + ":" + item);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(1500);
                List<String> list = new ArrayList<>();
                list.add("B1");
                list.add("B2");
                list.add("B3");

                System.out.println("交换前B的数据为：");
                for (String item : list) {
                    System.out.println("B" + ":" + item);
                }
                Thread.sleep(1500);
                list = exgr.exchange(list);//交换数据

                Thread.sleep(1500);
                System.out.println("交换后B的数据为：");
                for (String item : list) {
                    System.out.println("B" + ":" + item);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}